<template>
  <div>
    <!-- 开始生产弹出框 -->
    <el-dialog
      :title="dialogFormTitle"
      :visible.sync="dialogFormVisible"
      @close="closedialog"
    >
      <el-form
        ref="produceForm"
        :rules="rules"
        :model="productionproducedmodify"
        label-width="80px"
        style="width: 300px"
      >
        <el-form-item label="生产单号" prop="order.id" v-if="isshow">
          <el-select
            v-model="productionproducedmodify.order.id"
            filterable
            placeholder="请选择生产单号"
            @change="selectOrder"
          >
            <el-option
              v-for="item in poids"
              :key="item.value"
              :label="item.poid"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="生产员工" prop="employee.ename" v-if="isshow">
          <el-select
            v-model="productionproducedmodify.employee.ename"
            filterable
            placeholder="请选择生产员工"
            clearable
          >
            <el-option
              v-for="item in employees"
              :key="item.value"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="预计结束" prop="etime">
          <el-input
            type="date"
            v-model="productionproducedmodify.etime"
          ></el-input>
        </el-form-item>

        <el-form-item label="生产状态" prop="order.pstate" v-if="isshowstate">
          <el-select
            v-model="productionproducedmodify.order.pstate"
            filterable
            placeholder="请选择生产状态"
          >
            <el-option label="生产" value="生产中"></el-option>
            <el-option label="暂停" value="暂停中"></el-option>
            <el-option label="完成" value="已结束"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="生产日期" prop="stime">
          {{ productionproducedmodify.stime }}
        </el-form-item>

        <el-form-item label="产品名称" v-if="isshow">
          {{ productionproducedmodify.order.pname }}
        </el-form-item>

        <el-form-item label="预计产量" v-if="isshow">
          {{ productionproducedmodify.order.yield }}
        </el-form-item>
        
        <el-form-item label="生产原料1" v-if="isshow">
          {{productionproducedmodify.raws[2] }}
        </el-form-item>

        <el-form-item label="生产原料2" v-if="isshow">
          {{ productionproducedmodify.raws[3] }}
        </el-form-item>
        <el-form-item label="生产原料3" v-if="isshow">
          {{ productionproducedmodify.raws[4] }}
        </el-form-item>
        <el-form-item label="生产原料4" v-if="isshow">
          {{ productionproducedmodify.raws[5] }}
        </el-form-item>
        <el-form-item label="生产原料5" v-if="isshow">
          {{ productionproducedmodify.raws[6] }}
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeProduced">取 消</el-button>
        <el-button type="primary" @click="handEditAdd">确定</el-button>
      </div>
    </el-dialog>

    <!-- 完成弹出框 -->
    <el-dialog
      :title="dialogFormOverTitle"
      :visible.sync="dialogFormOverVisible"
      @close="closedialog"
    >
      <el-form
        ref="produceOverForm"
        :rules="rules"
        :model="productionover"
        label-width="80px"
        style="width: 300px"
      >
        <el-form-item label="生产单号">
          {{ productionover.order.poid }}
        </el-form-item>

        <el-form-item label="预计产量">
          {{ productionover.order.yield }}
        </el-form-item>

        <el-form-item label="实际产量" prop="order.prnum">
          <el-input v-model="productionover.order.prnum"></el-input>
        </el-form-item>

        <el-form-item label="产品单位" prop="order.prunit">
          <el-select
            v-model="productionover.order.prunit"
            filterable
            placeholder="请选择产品单位"
            clearable
          >
            <el-option label="千克" value="千克"></el-option>
            <el-option label="吨" value="吨"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="生产员工" prop="employee.ename">
          {{ productionover.employee.ename }}
        </el-form-item>

        <el-form-item label="结束日期">
          {{ productionover.order.ertime }}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeOver">取 消</el-button>
        <el-button type="primary" @click="handOver">确定</el-button>
      </div>
    </el-dialog>

    <!-- 搜索表单 -->
    <el-form
      ref="productionproducedForm"
      :model="productionproduced"
      label-width="80px"
      :inline="true"
    >
      <el-form-item>
        <el-button type="primary" @click="batchDelete">批量删除</el-button>
      </el-form-item>

      <el-form-item label="生产单号">
        <el-input v-model="productionproduced.order.poid" clearable></el-input>
      </el-form-item>

      <el-form-item label="产品名称">
        <el-input v-model="productionproduced.order.pname" clearable></el-input>
      </el-form-item>

      <el-form-item label="生产状态" style="width: 120px">
        <el-select v-model="productionproduced.order.pstate" placeholder="请选择状态">
          <el-option label="生产中" value="生产中"></el-option>
          <el-option label="暂停中" value="暂停中"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="生产日期">
        <el-input
          type="date"
          v-model="productionproduced.stime"
          clearable
        ></el-input>
      </el-form-item>

      <el-form-item label="生产员工">
        <el-input
          v-model="productionproduced.employee.ename"
          clearable
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询所有信息</el-button>
        <el-button @click="handAdd">开始生产</el-button>
        <el-button @click="clearAllFields">清空</el-button>
      </el-form-item>
    </el-form>

    <!-- 展示数据 -->
    <el-table
      :data="pageBean.beanList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column
        prop="order.poid"
        label="生产单号"
        width="140"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="order.pname"
        label="产品名称"
        width="100"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="order.yield"
        label="生产数量"
        width="100"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="order.punit"
        label="产品单位"
        width="100"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="employee.ename"
        label="生产员工"
        width="100"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="stime" label="生产日期" width="140" align="center">
      </el-table-column>
      <el-table-column
        prop="etime"
        label="预计结束日期"
        width="140"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="order.pstate"
        label="生产状态"
        width="140"
        align="center"
      >
      <template slot-scope="scope">
            <el-tag :type="scope.row.order.pstate === '生产中' ? 'success' : scope.row.order.pstate === '待生产' ? 'primary' : 'danger'" disable-transitions>{{scope.row.order.pstate}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 展示页码 -->
    <div class="block">
      <span class="demonstration"></span>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageIndex"
        :page-sizes="[1, 3, 6]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageBean.totalRecord"
      >
      </el-pagination>
    </div>
  </div>
</template>
  
  <script>
import axios from "axios";

export default {
  data() {
    var checketime = (rule, value, callback) => {
      if (new Date(value) < new Date(this.currentDate())) {
          callback(new Error("结束时间不能早于开始时间"));
        }else {
        callback();
      }
      };
      var checkenum = (rule, value, callback) => {
      if (value === undefined || value === "") {
        callback(new Error("填写数量"));
      } else if (!/^[1-9]\d*$/.test(value)) {
        callback(new Error("数量格式错误"));
      } else if(this.productionover.order.prunit ===this.productionover.order.punit && value > this.productionover.order.pnum){
        callback(new Error("实际产量不能高于预计产量"));
      }else {
        callback();
      }
    };
    var checkeprunit = (rule, value, callback) => {
      if (value !== this.productionover.order.punit && this.productionover.order.punit === "千克") {
        callback(new Error("实际产量不能高于预计产量"));
      } else {
        callback();
      }
    };
    return {
      isshowstate: true,
      isshow: false,
      produceForm: null,
      dialogFormVisible: false,
      dialogFormOverVisible: false,
      multipleSelection: [],
      dialogFormTitle: "",
      dialogFormOverTitle: "",
      pageIndex: 1,
      pageSize: 6,
      pageBean: {},
      departments: {},
      goods: {},
      poids: {},
      employees: {},
      rules: {
        "order.id": [
          { required: true, message: "请选择生产单号", trigger: "change" },
        ],
        'employee.ename': [
          { required: true, message: "请选择生产员工", trigger: "change" },
        ],
        "order.punit": [
          { required: true, message: "请选择产品单位", trigger: "change" },
        ],
        "order.prunit": [
          { required: true, message: "请选择产品单位", trigger: "change" },
          { validator: checkeprunit, trigger: "change" },
        ],
        "order.pnum": [
          { required: true, message: "请输入预计产量", trigger: "blur" },
        ],
        "order.prnum": [
          { required: true, message: "请输入实际产量", trigger: "blur" },
          { validator: checkenum, trigger: "blur" },
        ],
        "order.pstate": [
          { required: true, message: "请选择生产状态", trigger: "change" },
        ],
        etime: [
          {
            required: true,
            message: "请选择结束日期",
            trigger: "change",
          },
          { validator: checketime, trigger: "change" }
        ],
      },
      productionproduced: {
        order: {
          id: null,
          poid: null,
          pname: null,
        },
        employee: {
          id: null,
          ename: null,
        },
      },
      productionproducedmodify: {
        order: {
          id: null,
          poid: null,
          pstate: "",
          pname: "",
          punit: "",
          pnum: "",
        },
        employee: {
          id:null,
          ename: null,
        },
        stime: "",
        etime: "",
        raws: [],
      },
      productionover: {
        order: {
          id: null,
          poid: null,
          pname: "",
          punit: "",
          prunit: "",
          pnum: "",
          prnum: "",
          ertime: "",
        },
        employee: {
          ename: null,
        },
      },
    };
  },
  mounted() {
    this.getAll();
    this.getAllGoods();
    this.getAllPoids();
  },
  methods: {
    //  获取当前时间
    currentDate() {
      return (
        new Date().getFullYear() +
        "-" +
        ("0" + (new Date().getMonth() + 1)).slice(-2) +
        "-" +
        ("0" + new Date().getDate()).slice(-2)
      );
    },
    //  完成生产
    handOver(){
      this.$refs.produceOverForm.validate((valid) => {
          if (valid) {
            axios
              .post("/produced/overProduced", this.productionover)
              .then((resp) => {
                if (resp.data.code == 200) {
                  this.$message("创建成功");
                  this.getAll();
                } else {
                  this.$message.error(JSON.stringify(resp.data.msg));
                }
                this.dialogFormVisible = false;
                this.dialogFormOverVisible = false;
              });
          } else {
            this.$message("验证失败");
          }
        });
    },
    //  获取当前时间
    currentDate() {
      return (
        new Date().getFullYear() +
        "-" +
        ("0" + (new Date().getMonth() + 1)).slice(-2) +
        "-" +
        ("0" + new Date().getDate()).slice(-2)
      );
    },
    // 查询所有生产信息
    getAll() {
      axios
        .post(
          "/produced/findAllProduced/" + this.pageIndex + "/" + this.pageSize,
          this.productionproduced
        )
        .then((resp) => {
          if (resp.data.code == 200) {
            this.pageBean = resp.data.data;
          }
        });
    },
    //  查询所有未生产的单号
    getAllPoids() {
      axios.post("/produced/findAllPoids").then((resp) => {
        this.poids = resp.data.data;
      });
    },
    //  查询生产单对应的产品及原料
    selectOrder(value) {
      axios.post("/produced/findOrderByPoid/" + value).then((resp) => {
        let map = resp.data.data;
        // 获取map的key
        let keys = Object.keys(map);
        this.productionproducedmodify.order.pname = keys[0];
        // 获取key对应的values
        let values = keys.map((key) => map[key]);
        this.productionproducedmodify.raws = values[0];
        this.productionproducedmodify.order.yield =
          this.productionproducedmodify.raws[1];

          let employeename = this.productionproducedmodify.raws[0];
          this.employees = employeename.split("、");
      });
    },
    // 查询所有产品
    getAllGoods() {
      axios.post("/produced/findAllGoods").then((resp) => {
        this.goods = resp.data.data;
      });
    },
    //  查询按钮
    onSubmit() {
      this.pageIndex = 1;
      this.pageSize = 6;
      this.getAll();
    },
    //  一键清空
    clearAllFields() {
      this.productionproduced = {
        order: {},
        employee: {},
      };
      this.getAll();
    },
    //  添加弹出框
    handAdd() {
      this.dialogFormVisible = true,
      this.dialogFormTitle = "开始生产",
      this.isshow = true;
      this.isshowstate = false;
      this.getAllPoids();
      this.productionproducedmodify.stime=this.currentDate();
    },
    //  添加生产单
    handEditAdd() {
      this.$refs.produceForm.validate((valid) => {
        if (valid) {
          if (this.dialogFormTitle == "开始生产") {
            axios
              .post("/produced/addProduced", this.productionproducedmodify)
              .then((resp) => {
                if (resp.data.code == 200) {
                  this.$message("结束生产");
                  this.getAll();
                } else {
                  this.$message.error(JSON.stringify(resp.data.msg));
                }
                this.closeProduced();
              });
          }else if (this.productionproducedmodify.order.pstate === "已结束") {
            this.dialogFormOverVisible = true;
            this.dialogFormOverTitle = "完成生产"; 
          }else{
            axios
            .post("/produced/modifyProduced", this.productionproducedmodify)
            .then((resp) => {
              if (resp.data.code == 200) {
                this.$message("修改成功");
                this.getAll();
              } else {
                this.$message.error(JSON.stringify(resp.data.msg));
              }
            });
          this.dialogFormVisible = false;
          }
        }else {
          this.$message("验证失败");
        }
      })
    },
    //  编辑生产单
    handEdit(index, row) {
      this.dialogFormVisible = true;
      this.dialogFormTitle = "修改生产情况";
      axios.post("/produced/findProduced/" + row.id).then((resp) => {
        if (resp.data.code == 200) {
          this.productionproducedmodify = resp.data.data;
          this.productionover = resp.data.data;
          this.productionover.order.ertime = this.currentDate();
        }
      });
    },
    //  是否可编辑状态
    ishow() {
      return this.productionproducedmodify.pstate === "已结束";
    },
    //  关闭完成生产
    closeOver(){
      this.dialogFormOverVisible = false;
      this.dialogFormVisible = false;
      this.$refs.produceOverForm.clearValidate();
    },
    //  关闭开始生产
    closeProduced(){
      this.$refs.produceForm.resetFields();
      this.dialogFormVisible = false;
    },
    //  关闭弹出框
    closedialog() {
      //  清空数据
      this.productionproducedmodify={
        order: {
          id: null,
          poid: null,
          pstate: "",
          pname: "",
          punit: "",
          pnum: "",
        },
        employee: {
          id:null,
          ename: null,
        },
        stime: "",
        etime: "",
        raws: [],
      },
      this.isshowstate = true;
      this.isshow = false;
    },
    //  复选框选中
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 分页
    handleSizeChange(val) {
      //  重新查询
      this.pageSize = val;
      this.getAll();
    },
    handleCurrentChange(val) {
      //  重新查询
      this.pageIndex = val;
      this.getAll();
    },
    //  删除
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios.post("/produced/deleteP", row).then((resp) => {
            if (resp.data.code == 200) {
              this.$message("删除成功");
              this.getAll();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //  批量删除
    batchDelete(index, row) {
      if (this.multipleSelection.length > 0) {
        let myids = [];
        for (let i = 0; i < this.multipleSelection.length; i++) {
          myids.push(this.multipleSelection[i].id);
        }
        this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            axios
              .post("/produced/deletebatchgetP", { ids: myids })
              .then((resp) => {
                if (resp.data.code == 200) {
                  this.$message("删除成功");
                  this.getAll();
                } else {
                  this.$message.error("删除失败");
                }
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      } else {
        this.$message.error("请选择要删除的数据");
      }
    },
  },
};
</script>
  
  <style>
</style>